﻿using Language.Resource;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using System.Globalization;
using System.Linq;
using System.Net;
using VisionCloud.Domain.Common;

namespace VisionCloud.Domain.Filters
{
    /// <summary>
    /// 入参过滤器
    /// </summary>
    public class ParameterFilterAttribute : ActionFilterAttribute
    {
        private readonly IStringLocalizer<ControllerResource> localizer;

        public ParameterFilterAttribute(IStringLocalizer<ControllerResource> localizer)
        {
            this.localizer = localizer;
        }

        /// <summary>
        /// action执行之前
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
                return;
            var modelState = context.ModelState.FirstOrDefault(f => f.Value.Errors.Any());
            string errorMsg = modelState.Value.Errors.First().ErrorMessage;

            var culture = CultureInfo.CurrentCulture;
            var message = string.Format($"【{modelState.Key}】{localizer["YB0138"].Value}", localizer[errorMsg].Value);
            var apiResult = new ApiResult() { Code = AjaxCode.Fail, Message = message };
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            context.HttpContext.Response.ContentType = "application/json";
            context.Result = new JsonResult(apiResult);
        }
    }
}